<template>
  <div>
    <a-card>
      <a-form
        ref="modifyPriceForm"
        :model="couponData"
        :style="{ width: '100%' }"
        layout="horizontal"
        auto-label-width
      >
        <div class="base-info-item">
          <h4>基本信息</h4>
          <div class="form-item-view">
            <a-form-item
              field="promotionName"
              label="活动名称"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="couponData.promotionName"
                :disabled="disabled"
                allow-clear
                :style="{ width: '260px' }"
              />
            </a-form-item>
            <a-form-item
              field="couponName"
              label="优惠券名称"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="couponData.couponName"
                :disabled="disabled"
                allow-clear
                :style="{ width: '260px' }"
              />
            </a-form-item>
            <a-form-item field="couponType" label="优惠券类型">
              <a-select
                v-model="couponData.couponType"
                :style="{ width: '260px' }"
                :disabled="disabled"
              >
                <a-option
                  v-for="item of couponType"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </a-select>
            </a-form-item>
            <a-form-item
              v-if="couponData.couponType == 'DISCOUNT'"
              field="couponDiscount"
              label="折扣"
            >
              <a-input
                v-model="couponData.couponDiscount"
                :disabled="disabled"
                allow-clear
                :style="{ width: '260px' }"
              />
              <span class="describe">请输入0-10之间数字,可以输入一位小数</span>
            </a-form-item>
            <a-form-item
              v-if="couponData.couponType == 'PRICE'"
              field="price"
              label="面额"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="couponData.price"
                :disabled="disabled"
                allow-clear
                :style="{ width: '260px' }"
              />
            </a-form-item>
            <a-form-item field="getType" label="活动类型">
              <a-select
                v-model="couponData.getType"
                :style="{ width: '260px' }"
                :disabled="disabled"
              >
                <a-option
                  v-for="item of activityType"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </a-select>
            </a-form-item>
            <a-form-item
              v-if="couponData.getType === 'FREE'"
              field="publishNum"
              label="发放数量"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="couponData.publishNum"
                :disabled="disabled"
                allow-clear
                :style="{ width: '260px' }"
              />
              <div class="tips">如果发放数量为0时,则代表不限制发放数量</div>
            </a-form-item>
            <a-form-item
              v-if="couponData.getType === 'FREE'"
              field="couponLimitNum"
              label="领取数量限制"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="couponData.couponLimitNum"
                :disabled="disabled"
                allow-clear
                :style="{ width: '260px' }"
              />
              <div class="tips">如果领取数量为0时,则代表不限制领取数量</div>
            </a-form-item>
            <a-form-item
              field="description"
              label="范围描述"
              :disabled="disabled"
              :rules="[REQUIRED]"
            >
              <a-textarea
                v-model="couponData.description"
                allow-clear
                style="width: 260px"
                :max-length="50"
                show-word-limit
              />
            </a-form-item>
          </div>
          <h4>使用限制</h4>
          <div class="form-item-view">
            <a-form-item
              field="consumeThreshold"
              label="消费门槛"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="couponData.consumeThreshold"
                :disabled="disabled"
                allow-clear
                :style="{ width: '260px' }"
              />
            </a-form-item>

            <a-form-item field="rangeTime" label="有效期">
              <a-radio-group v-model="rangeTimeType">
                <a-radio
                  v-if="couponData.getType !== 'ACTIVITY'"
                  :disabled="disabled"
                  :value="1"
                  >起止时间</a-radio
                >
                <a-radio
                  v-if="couponData.getType === 'ACTIVITY'"
                  :disabled="disabled"
                  :value="0"
                  >固定时间</a-radio
                >
              </a-radio-group>
            </a-form-item>
            <a-form-item
              v-if="rangeTimeType === 1"
              field="rangeTime"
              label="有效期"
              :rules="[REQUIRED]"
            >
              <a-range-picker
                v-model="couponData.rangeTime"
                style="width: 254px; margin-bottom: 20px"
                :disabled="disabled"
              />
            </a-form-item>
            <a-form-item
              v-if="rangeTimeType === 0"
              field="effectiveDays"
              label="有效期"
            >
              <a-input-number
                v-model="couponData.effectiveDays"
                :style="{ width: '260px' }"
                class="input-demo"
                :min="1"
                :max="365"
                :disabled="disabled"
              />
              <span class="describe"
                >领取当天开始几天内有效(1-365间的整数)</span
              >
            </a-form-item>

            <a-form-item field="scopeType" label="使用范围">
              <a-radio-group
                v-model="couponData.scopeType"
                type="button"
                :disabled="disabled"
              >
                <a-radio value="ALL"> 全品类 </a-radio>
                <a-radio value="PORTION_GOODS"> 指定商品 </a-radio>
                <a-radio value="PORTION_GOODS_CATEGORY"> 部分商品分类 </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item v-if="couponData.scopeType == 'PORTION_GOODS'">
              <div style="display: flex; margin-bottom: 10px">
                <a-button
                  :disabled="disabled"
                  type="outline"
                  @click="openSkuList"
                  >选择商品</a-button
                >
                <a-button
                  :disabled="disabled"
                  style="margin-left: 10px"
                  type="outline"
                  status="danger"
                  @click="delSelectGoods"
                  >批量删除</a-button
                >
              </div>
            </a-form-item>
            <a-form-item v-if="couponData.scopeType == 'PORTION_GOODS'">
              <tablePage
                :columns="columns"
                :methods="methods"
                :data-list="couponData.promotionGoodsList"
                :checkbox="true"
                :bordered="true"
                :default-selected-keys="selectedKeys"
                :enable-pagination="false"
                @selectionChanges="
                  (val) => {
                    selectedKeys = val;
                  }
                "
              >
                <template #operation="{ rowIndex }">
                  <a-button
                    type="text"
                    status="danger"
                    :disabled="disabled"
                    @click="delGoods(rowIndex)"
                    >删除</a-button
                  >
                </template>
              </tablePage>
            </a-form-item>
            <a-form-item
              v-if="couponData.scopeType == 'PORTION_GOODS_CATEGORY'"
            >
              <a-cascader
                v-model:model-value="couponData.scopeIdGoods"
                :options="goodsCategoryList"
                :style="{ width: '260px' }"
                :disabled="disabled"
                allow-clear
                :path-mode="true"
              />
            </a-form-item>
          </div>
        </div>
      </a-form>
      <a-button style="margin-right: 5px" @click="closeCurrentPage"
        >返回</a-button
      >
      <a-button v-if="!disabled" type="primary" @click="handleSubmit"
        >提交</a-button
      >
    </a-card>
    <skuselect
      ref="skuSelect"
      :goods-or-sku="true"
      :default-goods-selected-list="couponData.promotionGoodsList"
      @change="changSkuList"
    ></skuselect>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue';
  import skuselect from '@/components/goods-sku-selector/index.vue';
  import { Message } from '@arco-design/web-vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { getGoodsCategoryAll } from '@/api/goods';
  import {
    saveShopCoupon,
    getShopCoupon,
    editShopCoupon,
  } from '@/api/promotion';
  import { useRouter, useRoute } from 'vue-router';
  import tablePage from '@/components/table-pages/index.vue';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import { dayFormatHHssMM, unixToDate } from '@/utils/filters';
  import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';

  const modifyPriceForm = ref();
  const router = useRouter();
  const route = useRoute();
  const rangeTimeType = ref<number>(1); // 当前时间类型
  const goodsCategoryList = ref([]) as any; // 商品分类列表
  const couponData = ref({
    /** 发行数量 */
    publishNum: 0,
    /** 运费承担者 */
    scopeType: 'ALL',
    /** 限领数量 */
    couponLimitNum: 1,
    /** 活动类型 */
    couponType: 'PRICE',
    /** 优惠券名称 */
    couponName: '',
    promotionName: '',
    getType: 'FREE',
    promotionGoodsList: [
      // goodsName: '',
      // price: '',
      // quantity: '',
      // originalPrice: '',
      // storeId: '',
      // storeName: '',
      // skuId: '',
      // categoryPath: '',
      // thumbnail: '',
      // goodsType: '',
      // goodsId: '',
      // originPrice: '',
    ],
    scopeIdGoods: [],
    rangeDayType: 'FIXEDTIME',
    couponDiscount: '',
    price: '',
    description: '',
    consumeThreshold: '',
    rangeTime: '',
    effectiveDays: '',
  }) as any;
  const getCagetoryList = async () => {
    const res = await getGoodsCategoryAll();
    if (res.data.success) {
      goodsCategoryList.value = res.data.result;
      goodsCategoryList.value = goodsCategoryList.value.map((item: any) => {
        if (item.children) {
          item.children = item.children.map((child: any) => {
            if (child.children) {
              child.children = child.children.map((son: any) => {
                return {
                  value: son.id,
                  label: son.name,
                };
              });
            }
            return {
              value: child.id,
              label: child.name,
              children: child.children || null,
            };
          });
        }
        return { value: item.id, label: item.name, children: item.children };
      });
    }
  };
  // 获取单个优惠券
  const getCoupon = async () => {
    const res = await getShopCoupon(route.query.id);
    if (res.data.success) {
      const data = res.data.result;
      couponData.value = res.data.result;
      if (couponData.value.scopeId) {
        couponData.value.scopeIdGoods = couponData.value.scopeId.split(',');
        // couponData.value.scopeIdGoods = couponData.value.scopeId.split(',').length === 3?couponData.value.scopeId.split(','):[];
      }
      if (data.startTime && data.endTime) {
        couponData.value.rangeTime = [
          unixToDate(Number(new Date(data.startTime)) / 1000, 'yyyy-MM-dd'),
          unixToDate(Number(new Date(data.endTime)) / 1000, 'yyyy-MM-dd'),
        ];
      }

      if (!data.promotionGoodsList) data.promotionGoodsList = [];
      rangeTimeType.value = data.rangeDayType === 'DYNAMICTIME' ? 0 : 1;
      // if (data.scopeType == "PORTION_GOODS_CATEGORY") {
      //   const prevCascader = data.scopeId.split(",");
      //   function next(params, prev) {
      //     for (let i = 0; i < params.length; i++) {
      //       const item = params[i];
      //       if (item.children) {
      //         next(item.children, [...prev, item]);
      //       } else {
      //         if (prevCascader.includes(item.id)) {
      //           prevCascader = prevCascader.map((key) => {
      //             if (key === item.id) {
      //               let result = prev.map((item) => item.id);

      //               return [...result, item.id];
      //             } else {
      //               return key;
      //             }
      //           });
      //         } else {
      //           i === params.length - 1 && (prev = []);
      //         }
      //       }
      //     }
      //   }
      // }
    }
  };
  onMounted(async () => {
    getCagetoryList();
    if (route.query.id) {
      getCoupon();
    }
  });

  // 表格的行选择器配置
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    // selectedRowKeys: [],
    onlyCurrent: true,
  });
  const selectedKeys = ref([]);
  // 表格
  const columns = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      // width: 300
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      // width: 300
    },
    {
      title: '库存',
      dataIndex: 'quantity',
      // width: 300
    },
  ];
  const methods: MethodsRule = {
    title: '操作',
    width: 250,
    fixed: 'right',
    methods: [{ title: '操作', slot: true, slotTemplate: 'operation' }],
  };
  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const skuSelect = ref(null) as any; // 商品选择器
  const disabled = ref(route.query.onlyView) as any;
  const rowkey = ref([]); // 所选行key

  // 优惠券类型
  const couponType = [
    {
      value: 'DISCOUNT',
      label: '打折',
    },
    {
      value: 'PRICE',
      label: '减免现金',
    },
  ];
  // 活动类型
  const activityType = [
    {
      value: 'FREE',
      label: '免费领取',
    },
    {
      value: 'ACTIVITY',
      label: '活动赠送',
    },
  ];
  // 打开商品选择器
  const openSkuList = () => {
    skuSelect.value.modalData.visible = true;
  };
  // 商品选择器数据
  const changSkuList = (val: any) => {
    couponData.value.promotionGoodsList = [];
    val.forEach((e: any) => {
      couponData.value.promotionGoodsList.push({
        goodsName: e.goodsName,
        price: e.price,
        quantity: e.quantity,
        originalPrice: e.price,
        storeId: e.storeId,
        storeName: e.storeName,
        skuId: e.id,
        categoryPath: e.categoryPath,
        thumbnail: e.small,
        goodsType: e.goodsType,
        goodsId: e.goodsId,
        originPrice: e.price,
        id: e.id || e.goodsId,
      });
    });
    couponData.value.promotionGoodsList =
      couponData.value.promotionGoodsList.map((v: any, index: any) => {
        return {
          ...v,
          key: index + 1,
        };
      });
  };
  // 多选删除商品
  const delSelectGoods = () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('您还未选择要删除的数据！');
      return;
    }
    const res = JSON.parse(JSON.stringify(selectedKeys.value));

    modal.confirm({
      title: '确认删除',
      content: '您确认要删除所选商品吗?',
      alignCenter: false,
      onOk: () => {
        couponData.value.promotionGoodsList =
          couponData.value.promotionGoodsList.filter((item: any) => {
            return !res.includes(item.skuId);
          });
      },
    });
  };
  const filterCategoryId = (list: any, idArr: any) => {
    // 递归获取分类id
    list.forEach((e: any) => {
      if (e instanceof Array) {
        filterCategoryId(e, idArr);
      }
      if (!Array.isArray(e)) {
        if (!idArr.includes(e)) {
          idArr.push(e);
        }
      }
    });
    return idArr;
  };
  // 返回上一页
  const routerpreviousPage = () => {
    router.push({ name: 'coupon' });
  };
  // 删除表格数据
  const delGoods = (idx: any) => {
    couponData.value.promotionGoodsList.splice(idx, 1);
  };
  // 选择行
  const selectTableChanges = (record: any) => {
    // console.log(record, 'val');
    // rowkey.value.push(...val)
  };
  // 返回
  const closeCurrentPage = () => {
    routerpreviousPage();
  };
  // 提交
  const handleSubmit = async () => {
    const auth = await modifyPriceForm.value?.validate();
    if (!auth) {
      const params = JSON.parse(JSON.stringify(couponData.value));
      // 判断当前活动类型
      params.getType != 'ACTIVITY' ? delete params.effectiveDays : '';
      if (rangeTimeType.value == 1) {
        params.rangeDayType = 'FIXEDTIME';
        params.startTime = dayFormatHHssMM(couponData.value.rangeTime[0]);
        params.endTime = dayFormatHHssMM(couponData.value.rangeTime[1]);
        delete params.rangeTime;
      } else {
        params.rangeDayType = 'DYNAMICTIME';
        delete params.rangeTime;
      }
      let scopeId = [] as any;
      if (
        params.scopeType == 'PORTION_GOODS' &&
        (!params.promotionGoodsList || params.promotionGoodsList.length == 0)
      ) {
        Message.warning('请选择指定商品');
        return;
      }
      if (
        params.scopeType == 'PORTION_GOODS_CATEGORY' &&
        (!params.scopeIdGoods || params.scopeIdGoods.length == 0)
      ) {
        Message.warning('请选择商品分类');
        return;
      }
      if (params.scopeType == 'PORTION_GOODS') {
        // 指定商品
        params.promotionGoodsList = params.promotionGoodsList.map((item: any) => {
          scopeId.push(item.skuId);
          const temp = {
            goodsName: item.goodsName,
            originalPrice: item.originalPrice,
            price: item.price,
            quantity: item.quantity,
            skuId: item.skuId,
            storeId: item.storeId,
          };
          return temp;
        });
        params.scopeId = scopeId.toString();
      } else if (params.scopeType == 'ALL') {
        delete params.promotionGoodsList;
      } else if (params.scopeType == 'PORTION_GOODS_CATEGORY') {
        // 部分商品分类
        scopeId = filterCategoryId(params.scopeIdGoods, []);
        params.scopeId = scopeId.toString();
        delete params.promotionGoodsList;
      }
      delete params.scopeIdGoods;
      if (!route.query.id) {
        delete params.id;
        saveShopCoupon(params).then((res: any) => {
          if (res.data.success) {
            Message.success('优惠券发送成功');
            routerpreviousPage();
          }
        });
      } else {
        delete params.consumeLimit;
        delete params.updateTime;
        editShopCoupon(params).then((res) => {
          if (res.data.success) {
            Message.success('优惠券修改成功');
            routerpreviousPage();
          }
        });
      }
    }
  };

  watch(
    () => couponData.value.getType,
    (val) => {
      if (val == 'FREE') {
        rangeTimeType.value = 1;
      } else {
        rangeTimeType.value = 0;
      }
      if (rangeTimeType.value == 0) {
        delete couponData.value.rangeTime;
      }
    },
    { deep: true, immediate: true }
  );
</script>

<style lang="less" scoped>
  h4 {
    margin-bottom: 10px;
    padding: 0 10px;
    border: 1px solid #ddd;
    background-color: #f8f8f8;
    font-weight: bold;
    color: #333;
    font-size: 14px;
    line-height: 40px;
    text-align: left;
  }

  .describe {
    font-size: 12px;
    margin-left: 10px;
    color: #999;
  }

  .effectiveDays {
    font-size: 12px;
    color: #999;

    > * {
      margin: 0 4px;
    }
  }

  .tips {
    font-size: 12px;
    color: #999;
    margin-left: 5px;
  }
</style>
